﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

namespace Mindfor.Web
{
	/// <summary>
	/// Provides extension functions to NameValueCollection.
	/// </summary>
	public static class NameValueCollectionExtensions
	{
		/// <summary>
		/// Returns boolean value by key.
		/// </summary>
		/// <param name="nv">NameValueCollection to get value from.</param>
		/// <param name="key">Key.</param>
		/// <returns>Bool value or <c>Null</c> if not found.</returns>
		public static bool? EvalBool(this NameValueCollection nv, string key)
		{
			string val = nv[key];
			if (val != null)
			{
				int index = val.IndexOf(',');
				if (index >= 0)
					val = val.Substring(0, index);

				bool b = false;
				return bool.TryParse(val, out b) ? b : (bool?)null;
			}

			return null;
		}

		/// <summary>
		/// Returns integer value by key.
		/// </summary>
		/// <param name="nv">NameValueCollection to get value from.</param>
		/// <param name="key">Key.</param>
		/// <returns>Integer value or <c>Null</c> if not found.</returns>
		public static int? EvalInt(this NameValueCollection nv, string key)
		{
			string val = nv[key];
			if (val != null)
			{
				int i = 0;
				return int.TryParse(val, out i) ? i : (int?)null;
			}

			return null;
		}

		/// <summary>
		/// Returns html get params string. If not empty then starts with '?'.
		/// </summary>
		/// <param name="nv">NameValueCollection.</param>
		/// <returns>Html get params string.</returns>
		public static string ToHtmlGet(this NameValueCollection nv)
		{
			StringBuilder sb = new StringBuilder();
			if (nv.Count > 0)
				sb.Append('?');
			for (int i=0; i<nv.Count; i++)
			{
				if (i != 0)
					sb.Append('&');
				sb.Append(nv.GetKey(i));
				sb.Append('=');
				sb.Append(nv.Get(i));
			}
			return sb.ToString();
		}
	}
}
